package com.runfast.waimai.service.impl;

import com.runfast.common.exception.BaseException;
import com.runfast.common.service.BaseService;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.waimai.dao.model.RunfastGoodsSell;
import com.runfast.waimai.dao.model.RunfastGoodsSellStandard;
import com.runfast.waimai.dao.model.RunfastGoodsSellStandardExample;
import com.runfast.waimai.service.RunfastGoodsSellService;
import com.runfast.waimai.service.RunfastGoodsSellStandardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RunfastGoodsSellStandardServiceImpl extends BaseService<RunfastGoodsSellStandard, Integer, RunfastGoodsSellStandardExample> implements RunfastGoodsSellStandardService {

    @Autowired
    private RunfastGoodsSellService goodsSellService;

    @Override
    public void updateStock(Integer goodsId, Integer standarId, Integer num) {
        RunfastGoodsSellStandard standard = this.selectByPrimaryKey(standarId);

        Integer standardNum = standard.getNum();
        standardNum = standardNum == null ? 0 : standardNum;

        int stockNum = standardNum + num;
        if (stockNum < 0) throw new BaseException(ResultCode.FAIL, "商品库存不足");


        RunfastGoodsSellStandard standardUpdate = new RunfastGoodsSellStandard();
        standardUpdate.setId(standarId);
        standardUpdate.setNum(stockNum);

        this.updateByPrimaryKeySelective(standardUpdate);


        RunfastGoodsSell goodsSell = goodsSellService.selectByPrimaryKey(goodsId);
        Integer goodsSellNum = goodsSell.getNum();
        goodsSellNum = goodsSellNum == null ? 0 : goodsSellNum;

        int goodsStockNum = goodsSellNum + num;
        RunfastGoodsSell goodsSell1Update = new RunfastGoodsSell();
        goodsSell1Update.setId(goodsId);
        goodsSell1Update.setNum(goodsStockNum);

        goodsSellService.updateByPrimaryKeySelective(goodsSell1Update);


    }
}